module HC595_Driver(
	clk,
	rst_n,
	seg,
	sel,
	DIO,
	SRCLK,
	RCLK
);

	input clk;
	input rst_n;
	input [7:0] seg;
	input [7:0] sel;
	output reg DIO;
	output reg SRCLK;
	output reg RCLK;
	
	parameter CLOCK_FREQ = 50_000_000;
	parameter SRCLK_FREQ = 12_500_000;
	parameter MCNT = CLOCK_FREQ/(SRCLK_FREQ*2) - 1;
	reg [29:0] div_cnt;
	
	reg [4:0] cnt;
	
	always@(posedge clk or negedge rst_n)
		if(!rst_n)
			div_cnt <= 0;
		else if(div_cnt == MCNT)
			div_cnt <= 0;
		else
			div_cnt <= div_cnt + 1'd1;

	always@(posedge clk or negedge rst_n)
		if(!rst_n)
			cnt <= 0;
		else if(div_cnt == MCNT)
			cnt <= cnt + 1'd1;

	always@(posedge clk or negedge rst_n)
		if(!rst_n)begin
			DIO <= 0;
			SRCLK <= 0;
			RCLK <= 0;
		end else begin
			case(cnt)
				// 段选
				0:begin DIO <= seg[7]; SRCLK <= 0; RCLK <= 1; end
				1:begin SRCLK <= 1;RCLK <= 0; end
				2:begin DIO <= seg[6]; SRCLK <= 0; end
				3:SRCLK <= 1;
				4:begin DIO <= seg[5]; SRCLK <= 0; end
				5:SRCLK <= 1;
				6:begin DIO <= seg[4]; SRCLK <= 0; end
				7:SRCLK <= 1;
				8:begin DIO <= seg[3]; SRCLK <= 0; end
				9:SRCLK <= 1;
				10:begin DIO <= seg[2]; SRCLK <= 0; end
				11:SRCLK <= 1;
				12:begin DIO <= seg[1]; SRCLK <= 0; end
				13:SRCLK <= 1;
				14:begin DIO <= seg[0]; SRCLK <= 0; end
				15:SRCLK <= 1;
				// 位选
				16:begin DIO <= sel[7]; SRCLK <= 0; end
				17:SRCLK <= 1;
				18:begin DIO <= sel[6]; SRCLK <= 0; end
				19:SRCLK <= 1;
				20:begin DIO <= sel[5]; SRCLK <= 0; end
				21:SRCLK <= 1;
				22:begin DIO <= sel[4]; SRCLK <= 0; end
				23:SRCLK <= 1;
				24:begin DIO <= sel[3]; SRCLK <= 0; end
				25:SRCLK <= 1;
				26:begin DIO <= sel[2]; SRCLK <= 0; end
				27:SRCLK <= 1;
				28:begin DIO <= sel[1]; SRCLK <= 0; end
				29:SRCLK <= 1;
				30:begin DIO <= sel[0]; SRCLK <= 0; end
				31:SRCLK <= 1;
			endcase
		end
		
endmodule
